<?php
namespace app\api\model;
use think\Model;
use EasyWeChat\Factory;

class Wx
{
    private $config;
    private $app;

    public function __construct()
    {
        $epay = get_addon_config('epay');
        $this->config = [
            'app_id' => $epay['wechat']['miniapp_id'],
            'secret' => $epay['wechat']['app_secret'],

            // 下面为可选项
            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',

            'log' => [
                'level' => 'debug',
                'file' => __DIR__.'/wechat.log',
            ],
        ];
        $this->app = Factory::miniProgram($this->config);

    }

    /*
    *获取小程序的session_key
    */
    public function getSessionKey($code)
    {
        try{
            $session_key = $this->app->auth->session($code);
        }catch(\Exception $e){
            // dd($e);
             echo 'Message: ' .$e->getMessage();
            \think\Log::record('错误---'.$e->getMessage(),'notice');
        }
        return $session_key;

    }

    /*
    *微信小程序消息解密
    */
    public function decryptedData($session, $iv, $encryptedData)
    {
        $decryptedData = [];
        try{
            $decryptedData = $this->app->encryptor->decryptData($session, $iv, $encryptedData);
        }catch(\Exception $e){
            // dd($e);
            // echo 'Message: ' .$e->getMessage();
            \think\Log::record('错误---'.$e->getMessage(),'notice');
        }
        return $decryptedData;
    }

    public function getSignedPackage($url,$shop=[])
    {
        if ( $shop['app_id'] && $shop['tx_account_status'] ) {
            $this->appId = $shop['app_id'];
            $this->appSecret = $shop['wxapp_secret'];
        }
        $jsapiTicket = $this->getJsApiTicket();
        $timestamp = time();
        $nonceStr = Random::alnum(16);
        // 这里参数的顺序要按照 key 值 ASCII 码升序排序
        $string = "jsapi_ticket={$jsapiTicket}&noncestr={$nonceStr}&timestamp={$timestamp}&url={$url}";
        $signature = sha1($string);
        $signPackage = array(
            "appId"     => $this->appId,
            "nonceStr"  => $nonceStr,
            "timestamp" => $timestamp,
            "url"       => $url,
            "signature" => $signature,
            "rawString" => $string,
            "jsticket" => $jsapiTicket,
        );
        return $signPackage;
    }

    private function getJsApiTicket()
    {
        $ticket = Cache::get("wechat_jsapi_ticket".$this->appId);
        if (!$ticket) {
            $accessToken = $this->getAccessTokenNew();
            // 如果是企业号用以下 URL 获取 ticket
            // $url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token={$accessToken}";
            $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token={$accessToken}";
            $ret = Http::get($url);
            $json = json_decode($ret, true);
            $ticket = isset($json['ticket']) ? $json['ticket'] : '';
            if ($ticket) {
                Cache::set('wechat_jsapi_ticket'.$this->appId, $ticket, 7200);
            }
        }
        return $ticket;
    }

    private function getAccessToken()
    {
        $access_token = 'access_token'.$this->appId;
        $token = Cache::get($access_token);
        if (!$token) {
            // 如果是企业号用以下URL获取access_token
            // $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={$this->appId}&corpsecret={$this->appSecret}";
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appId}&secret={$this->appSecret}";
            $ret = Http::get($url);
            $json = json_decode($ret, true);
            $token = isset($json['access_token']) ? $json['access_token'] : '';
            if ($token) {
                Cache::set($access_token, $token, 7200);
            }
        }
        return $token;
    }

    /*
    *新的获取token方式
    */
    private function getAccessTokenNew()
    {
        $config =['app_id'=>$this->appId,'secret'=>$this->appSecret];
        $app = new Application($config);
        $accessToken = $app->access_token;
        $token = $accessToken->getToken(); // token 数组  token['access_token'] 字符串
        return $token;
    }

    /*
    *适用于需要的码数量极多，或仅临时使用的业务场景
     */
    public function getUnlimit($scene,$page,$env_version,$name="appcode")
    {
        $data = ['code'=>201,'msg'=>'请求失败','data'=>[]];
        try{
            $response = $this->app->app_code->getUnlimit($scene, [
                'page'  => $page,
                'env_version'=>$env_version,
                'width' => 600,
                'check_path'=>false,
            ]);
            if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
                $directory = '/www/wwwroot/api.ftugbawxapp.com/public/uploads/code';
                if (!is_dir($directory)) {
                    mkdir($directory, 0755, true); // @codeCoverageIgnore
                }
                // $filename = $response->saveAs($directory, $scene.'_'.$page.'_'.'appcode.png');
                if(!is_numeric($scene)){
                    $scene = md5($scene);
                }
                $filename = $response->saveAs($directory, $scene.'_'.$name.'.png');
            }

            if ( is_array($response) && isset($response['errcode']) ) {
                return $data;
            }
            $data['code'] = 200;
            $data['msg'] = '请求成功';
            $data['data'] = '/'.$directory.'/'.$filename;
        }catch(\Exception $e){
            \think\Log::record('错误---'.$e->getMessage(),'notice');
        }
        return $data;
    }
}
